public class Solution {
    public String compressString(String S) {
        if (S == null || "".equals(S)) {
            return S;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(S.charAt(0));
        int count = 1;
        for (int i = 1; i < S.length(); i++) {
            if (sb.charAt(sb.length() - 1) != S.charAt(i)) {
                sb.append(count).append(S.charAt(i));
                count = 1;
            } else {
                count++;
            }
        }
        return sb.append(count).length() < S.length() ? sb.toString() : S;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        String str = "aaabbcc";
        String res = s.compressString(str);
        System.out.println(res);
    }
}
